package com.general.framework.wukong.blockingQueue.interview;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        Interview interview = new Interview(queue);
        Thread interviewerThread = new Thread(interview.new Interviewer());
        Thread intervieweeThread = new Thread(interview.new Interviewee());
        interviewerThread.start();
        intervieweeThread.start();
    }
}

class Interview {
    private final BlockingQueue<String> queue;
    private final Object lock = new Object();
    private int remainingTasks = 10;

    public Interview(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    class Interviewer implements Runnable {
        @Override
        public void run() {
            for (int i = 1; i <= 10; i++) {
                try {
                    String candidate = "Candidate" + i;
                    queue.put(candidate);
                    System.out.println("已安排好了第 " + candidate + " 位候选者");
                    synchronized (lock) {
                        remainingTasks--;
                        if (remainingTasks == 0) {
                            lock.notifyAll();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class Interviewee implements Runnable {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    while (remainingTasks > 0) {
                        lock.wait();
                    }
                }
                while (true) {
                    String candidate = queue.take();
                    if (candidate == null) {
                        break;
                    }
                    System.out.println("第 " + candidate + " 位候选者面试完毕");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}